package com.zdj.question;

import java.util.Arrays;

/**
 * @author zdj
 * @date 2023-03-31 11:37
 */
//hide-start
public class MergeTwoList {
    public static void main(String[] args) {
        String[] sList1 = args[0].replaceAll("\\[|\\]| |\"", "").split(",");
        ListNode node1 = null;
        if (sList1.length > 0 && !"".equals(sList1[0])) {
            node1 = getNode(Arrays.stream(sList1).mapToInt(Integer::parseInt).toArray());
        }

        String[] sList2 = args[1].replaceAll("\\[|\\]| |\"", "").split(",");
        ListNode node2 = null;
        if (sList2.length > 0 && !"".equals(sList2[0])) {
            node2 = getNode(Arrays.stream(sList2).mapToInt(Integer::parseInt).toArray());
        }

        ListNode mergeList = MergeSolution.mergeTwoLists(node1, node2);

        String result = "[";
        while (mergeList != null) {
            result += mergeList.val + ",";
            mergeList = mergeList.next;
        }

        if(result.endsWith(",")) {
            result = result.substring(0, result.length()-1);
        }

        result += "]";

        System.out.print(result);
    }

    private static ListNode getNode(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode node = null;
        for (int item : arr) {
            // 节点为空创建节点后返回
            if (node == null) {
                node = new ListNode(item);
                continue;
            }
            ListNode tmp = node.next;
            // 下一个节点为空 增加下一个节点
            if (tmp == null) {
                node.addNext(new ListNode(item));
                continue;
            }
            // 下一个节点不为空 遍历找到为空的下一个节点 并给当前节点加下一个节点
            while (tmp != null) {
                ListNode t = tmp;
                tmp = tmp.next;
                if (tmp == null) {
                    t.addNext(new ListNode(item));
                }
            }
        }
        return node;
    }
}
//hide-end

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    public void addNext(ListNode next) {
        this.next = next;
    }
}
class MergeSolution {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 请将您的代码写到这里
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将链表末尾指向未合并完的链表即可
        prev.next = l1 == null ? l2 : l1;

        return prehead.next;
    }
}
